<?php
namespace Credit;
use Credit;
final class Auth
{
    private $appkey;
    private $secretKey;
    private $_userParam;
    protected $getUrl='';
    protected $format = 'json';
    public $Charset='UTF-8';
    public $postData = array();
    //protected $Mode
    protected $API_URL = 'https://api.limuzhengxin.com/api/gateway';//https://api.limuzhengxin.com/api/gateway
    public function __construct($appkey, $secretKey)
    {
        $this->appkey    = $appkey;
        $this->secretKey = $secretKey;
    }
    public function __set ($name, $value){
        $this->_userParam[$name] = $value;
    }
    protected function generateSign($params)    {
        $version = $params['version'];
        $params['version'] = $version.$this->secretKey;
        ksort($params);
        $sign=sha1(urldecode(http_build_query($params)));
        return $sign;
    }

    protected function system(){
        return [
            'ts'            =>  time()*1000, //时间戳，格式为yyyy-MM-dd HH:mm:ss
            'apiKey'        =>  $this->appkey, //TOP分配给应用的AppKey
            'version'       =>  '1.2.0', //API协议版本，可选值:2.0。
            'accessType'    =>  'api', //接入方式
            //'format'        =>  $this->format, //响应格式。默认json,目前支持格式为xml,json
        ];
    }
    static public function createStrParam ($paramArr)
    {
        $strParam = array();
        foreach ($paramArr as $key => $val) {
            if ($key != '' && $val != '') {
                $strParam []= $key . '=' . urlencode($val);
            }
        }
        $url = implode('&',$strParam);
        return $url;
    }
    protected function sign(){
        $data2          =   self::system();
        $data           =   array_merge($data2,$this->_userParam);
        $data['sign']   =   self::generateSign($data);
        $params         =   array_merge($data2,$data);
        return $params;
    }
    protected  function Url($mode){
        if(isset($this->_userParam['ApiUrl'])){
            $this->API_URL =   $this->_userParam['ApiUrl'];
            unset($this->_userParam['ApiUrl']);
        }

        $data = $this->sign();
        if($mode=='GET'){
        $strParam       = $this->createStrParam($data);
        $this->getUrl      = $this->API_URL.'?' . $strParam;
        }else{
            $this->getUrl      = $this->API_URL;
            $this->postData    =$data;
        }
    }

    public function Send ($mode = 'GET', $format = 'json'){
        $mode =  strtoupper($mode);
        $this->format = strtolower($format);
        $this->Url($mode);
        $data           =   new \Common\Extend\Api\GetData();
        $data->Mode     = $mode;
        $data->Url      = $this->getUrl;
        $data->format   = $format;
        $data->Charset  = $this->Charset;
        $data->postData = $this->postData;
        return $data;
    }


}
